package com.ptbuy.signature;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;


import com.ptbuy.MainActivity;
import com.ptbuy.R;
import com.ptbuy.utils.Constants;
import com.ptbuy.utils.Utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 2022年1月11日10:26:01
 * 增加
 */
public class SingDialogAcvity extends AppCompatActivity implements View.OnClickListener {


    LinePathView mPathView;
    Button mBtnClear, mBtnSave, mBtnDown;

    WebView webView;

    private String tag;
    private String monthDay;

    private ProgressDialog loadingDialog;


    private boolean target = false;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.appfor_qmgj);

        mPathView = findViewById(R.id.mPathView);
        mBtnDown = findViewById(R.id.mBtnDown);
        mBtnClear = findViewById(R.id.mBtnClear);
        mBtnSave = findViewById(R.id.mBtnSave);
        //修改背景、笔宽、颜色
        mPathView.clear();
        mPathView.setBackColor(Color.WHITE);
        mPathView.setPaintWidth(20);
        mPathView.setPenColor(Color.BLACK);

        target = false;

        //关闭
        mBtnDown.setOnClickListener(this);
        //清除
        mBtnClear.setOnClickListener(this);
        //保存
        mBtnSave.setOnClickListener(this);

        mPathView.clear();
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
        monthDay = formatter.format(date);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mBtnDown:  //签名工具 返回
                finish();
                break;
            case R.id.mBtnClear: //清除
                mPathView.clear();
                mPathView.setBackColor(Color.WHITE);
                mPathView.setPaintWidth(20);
                mPathView.setPenColor(Color.BLACK);
                break;
            case R.id.mBtnSave:  //保存
                if (!Utils.hasAllFilesAccess()) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(SingDialogAcvity.this);
                    builder.setTitle("提示");
                    builder.setMessage("没有写入文件的权限，需要打开文件所有权限才能导出成功，是否授权？");
                    builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @RequiresApi(api = Build.VERSION_CODES.R)
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            target = true;
                            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                            Uri uri = Uri.fromParts("package", Constants.CurrentContext.getPackageName(), null);
                            intent.setData(uri);
                            startActivity(intent);
                        }
                    });
                    builder.setNeutralButton("否", null);
                    builder.show(); //调用show()方法来展示对话框
                } else {
                    mySave();
                }
                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if(target){
            mySave();
        }
    }

    private void mySave() {
        try {
            loadingDialog = new ProgressDialog(this);
            loadingDialog.setMessage("正在保存签名...");
            loadingDialog.setTitle("请稍等");
            loadingDialog.show();
            Date date1 = new Date();
            SimpleDateFormat formatter_other = new SimpleDateFormat("yyyyMMddhhmmss", Locale.getDefault());
            String monthDay_other = formatter_other.format(date1);
            //先保存签名照片到本地
            String path = Constants.getMultPath() + monthDay_other + ".jpg";
            mPathView.save(path, true, 10);
            Intent intent1 = new Intent();
            intent1.putExtra("path", path);
            loadingDialog.dismiss();
            setResult(RESULT_OK, intent1);
            finish();
        } catch (Exception e) {
            Toast.makeText(SingDialogAcvity.this, "签名保存失败，请重新签名！", Toast.LENGTH_LONG).show();
            e.printStackTrace();
            loadingDialog.dismiss();
        }
    }

    /**
     * 2022年1月10日18:24:35
     * 图片旋转
     *
     * @param bm
     * @param orientationDegree
     * @return
     */
    private static Bitmap rotateBitmap2(Bitmap bm, int orientationDegree) {
        //方便判断，角度都转换为正值
        int degree = orientationDegree;
        if (degree < 0) {
            degree = 360 + orientationDegree;
        }

        int srcW = bm.getWidth();
        int srcH = bm.getHeight();

        Matrix m = new Matrix();
        m.setRotate(degree, (float) srcW / 2, (float) srcH / 2);
        float targetX, targetY;

        int destH = srcH;
        int destW = srcW;

        //根据角度计算偏移量，原理不明
        if (degree == 90) {
            targetX = srcH;
            targetY = 0;
            destH = srcW;
            destW = srcH;
        } else if (degree == 270) {
            targetX = 0;
            targetY = srcW;
            destH = srcW;
            destW = srcH;
        } else if (degree == 180) {
            targetX = srcW;
            targetY = srcH;
        } else {
            return bm;
        }

        final float[] values = new float[9];
        m.getValues(values);

        float x1 = values[Matrix.MTRANS_X];
        float y1 = values[Matrix.MTRANS_Y];

        m.postTranslate(targetX - x1, targetY - y1);

        //注意destW 与 destH 不同角度会有不同
        Bitmap bm1 = Bitmap.createBitmap(destW, destH, Bitmap.Config.ARGB_8888);
        Paint paint = new Paint();
        Canvas canvas = new Canvas(bm1);
        canvas.drawBitmap(bm, m, paint);
        return bm1;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String webPath = (String) msg.obj;
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            loadingDialog.dismiss();
                            Intent intent = new Intent(SingDialogAcvity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }, 1000 * 1);
                    break;
            }
        }
    };
}
